package com.tan.androidtest.customview.canvas;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Camera;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.View;

import com.tan.androidtest.R;

/**
 * 测试翻页效果
 */

public class DemoViewTest extends View {

    private Paint mPaint = new Paint();
    private Bitmap mBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.icon_test1);

    private float rotateDegree = 0f;//旋转的角度

    public float getRotateDegree() {
        return rotateDegree;
    }

    public void setRotateDegree(float rotateDegree) {
        this.rotateDegree = rotateDegree;
        invalidate();
    }

    public DemoViewTest(Context context) {
        super(context);
    }

    public DemoViewTest(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public DemoViewTest(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawMBitmap(canvas);
    }

    /**
     * 画Bitmap
     */
    private void drawMBitmap(Canvas canvas) {
        int startLeft = 100;
        int startTop = 100;
        int halfBitmapWidth = mBitmap.getWidth() / 2;
        int halfBitmapHeight = mBitmap.getHeight() / 2;

        //使用camera做三维的旋转
        canvas.save();
        //canvas.clipRect(0, halfBitmapHeigth, halfBitmapWidth * 2, halfBitmapHeigth * 2);
        Camera camera = new Camera();
        camera.save(); // 保存 Camera 的状态
        camera.rotateY(-rotateDegree); // 旋转 Camera 的三维空间
        canvas.translate(startLeft + halfBitmapWidth, startTop + halfBitmapHeight); // 旋转之后把投影移动回来
        camera.applyToCanvas(canvas); // 把旋转投影到 Canvas
        canvas.translate(-(startLeft + halfBitmapWidth), -(startTop + halfBitmapHeight)); // 旋转之前把绘制内容移动到轴心（原点）
        camera.restore();

        canvas.drawBitmap(mBitmap, startLeft, startTop, mPaint);
        canvas.restore();

        //裁切上半部分,并画bitmap
        canvas.save();
        canvas.clipRect(startLeft, startTop, startLeft + halfBitmapWidth, startTop + halfBitmapHeight * 2);
        canvas.drawBitmap(mBitmap, startLeft, startTop, mPaint);
        canvas.restore();


    }
}
